﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Zeta.Common;

namespace SarkothFarmer.Helpers
{
    class Stats
    {
        private int cellars, games;
        private List<TimeSpan> withCellar, withoutCellar;
        private StateManager state;
        public Stats(StateManager state)
        {
            cellars = 0;
            games = 0;
            withCellar = new List<TimeSpan>();
            withoutCellar = new List<TimeSpan>();
            this.state = state;
        }
        private double[] AllStats(List<TimeSpan> runs)
        {
            var min = runs[0].TotalSeconds;
            var max = runs[0].TotalSeconds;
            var count = 0;
            double total = 0;
            foreach (var time in runs)
            {
                count++;
                total += time.TotalSeconds;
                if (time.TotalSeconds < min)
                    min = time.TotalSeconds;
                if (time.TotalSeconds > max)
                    max = time.TotalSeconds;
            }
            return new[] { Math.Round(total / count, 1), Math.Round(min, 1), Math.Round(max, 1) };
        }

        private void PrintStats(TimeSpan thisRun)
        {
            Logger.WriteQuiet("Cellar found in {0}/{1} games, that's {2}%.", cellars, games, Math.Round((double)cellars / games * 100, 1));
            if (thisRun != TimeSpan.Zero)
            {
                if (state.Cellar)
                {
                    Logger.WriteQuiet("This run with cellar took {0} seconds.", Math.Round(thisRun.TotalSeconds, 1));
                }
                else
                {
                    Logger.WriteQuiet("This run without cellar took {0} seconds.", Math.Round(thisRun.TotalSeconds, 1));
                }
            }
            if (withCellar.Any())
            {
                var withCellarStats = AllStats(withCellar);
                Logger.WriteQuiet("Run with cellar - Avg: {0}s Min: {1}s Max {2}s.", withCellarStats[0], withCellarStats[1], withCellarStats[2]);
            }
            if (withoutCellar.Any())
            {
                var withoutCellarStats = AllStats(withoutCellar);
                Logger.WriteQuiet("Run without cellar - Avg: {0}s Min: {1}s Max {2}s.", withoutCellarStats[0], withoutCellarStats[1], withoutCellarStats[2]);
            }
        }

        public void AddRun(TimeSpan elapsed, bool cellar)
        {
            games++;
            if (cellar)
            {
                cellars++;
                withCellar.Add(elapsed);
            }
            else
            {
                withoutCellar.Add(elapsed);
            }
            PrintStats(elapsed);
        }
    }
}
